package com.com.typhoon.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.com.typhoon.util.JwtUtil;
import com.com.typhoon.util.ResponseUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shuya | dongfeng.zdf@alibaba-inc.com
 * @description
 * @date 2018/10/19 下午7:51
 * @description
 * @modified by
 * @since V2.0.0
 */
@Slf4j
public class CustomInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("CustomInterceptor.interceptor url:{}",request.getRequestURL());
        String token = request.getHeader("token");
        if(null == token || token.isEmpty()) {
            log.info("CustomInterceptor.interceptor token is emtpry,url={}",request.getRequestURL());
            this.putFailResult(response,"需要登录");
            return false;
        }
        Claims claims = null;
        try {
            claims = JwtUtil.parseJwt(token,JwtUtil.SALT);
        } catch (MalformedJwtException e) {
            log.error("CustomInterceptor.interceptor token is illegal;token={},url={}",token,request.getRequestURL(),e);
            this.putFailResult(response,"token非法");
            return false;
        } catch (ExpiredJwtException e) {
            log.error("CustomInterceptor.interceptor token is overdate;token={},url={}",token,request.getRequestURL());
            this.putFailResult(response,"token过期");
            return false;
        } catch (Exception e) {
            log.error("CustomInterceptor.interceptor token is invalid;token={},url={}",token,request.getRequestURL(),e);
            this.putFailResult(response,"token无效");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }

    private void putFailResult(HttpServletResponse response, String msg) {
        Map<String, Object> results = new HashMap<>();
        results.put("code", "error");
        results.put("msg", msg);
        ResponseUtils.renderJson(response, JSONObject.toJSONString(results, SerializerFeature.WriteMapNullValue));
    }
}
